<?php
class Entity_books extends CI_Controller{
	function __construct(){
		parent::__construct();
		//判断session
		if (!$this->session->userdata('name')){
			header("Location: /");
		}
	}
	
	function index(){
		$this->load->model('entity_books_model');
		$key = trim($this->input->get('key'));
		$pid = $this->input->get('pid');
		$offset = $this->input->get('offset');
		
		$where = array(
			'key' => $key,
			'pid' => $pid
		);
		
		$this->load->library('pagination');
		$page_config = render_pagination_config_array();	
		$page_config['base_url'] = '/entity_books/?key='.$key.'&pid='.$pid;
		$page_config['total_rows'] = $this->entity_books_model->get_all_rows($where);
		$this->pagination->initialize($page_config);
		$pager_link	= $this->pagination->create_links();
		
		$entity_books_list = $this->entity_books_model->get_consumable_by_page($page_config['per_page'],$offset,$where);
		
		$data['sidebar'] = array('editorial','entity_books');
		$data['query'] = $entity_books_list;
		$data['page'] = $pager_link;
		$data['search'] = $where;
		$a = array(''=>'未指定出版社');
		foreach(publishers_options() as $row){
			$a[$row['id']] = $row['publishername'];
		}
		$data['op'] = $a;
		load_view('entity_books',$data);
	}
	
	function new_entity_books(){
		$data['sidebar'] = array('editorial','entity_books/new_entity_books');
		$data['query'] = '';
		load_view('entity_books_file',$data);
	}
	
	function modify_entity_books($id){	
		$this->load->model('entity_books_model');
		$obj = new Entity_books_model($id);
		$data['sidebar'] = array('editorial','entity_books/modify_entity_books');
		$data['query'] = array(
			'id' => $id,
			'title' => $obj->title,
			'pid' => $obj->pid,
			'isbn' => $obj->isbn,
			'price' => $obj->price,
			'bought' => $obj->bought,
		);
		load_view('entity_books_file',$data);
	}
	
	function execute(){
		$id = $this->input->post('id');
		$title = trim($this->input->post('title'));
		$pid = $this->input->post('pid');
		$isbn = $this->input->post('isbn');
		$price = $this->input->post('price');
		$bought = strtotime($this->input->post('bought'));
	
		$this->load->model('entity_books_model');
		$obj = new Entity_books_model($id);
		$obj->title = $this->db->escape($title);
		$obj->pid = $pid;
		$obj->isbn = $isbn;
		$obj->price = $price;
		$obj->bought = $bought;
		
		if($id){
			$obj->update();
			$obj->update_ebook($id);
		}else{
			$obj->created = time();
			$obj->save();	
		}
		header("Location: /entity_books");
	}
	
	function del_entity_books($id){
		$this->load->model('entity_books_model');
		$obj = new Entity_books_model($id);
		$obj->delete();
		header("Location: /entity_books");
	}
}